<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3.防抖debounce</title>
</head>

<body>
  
  频繁操作最后触发

  <input type="text" id="input1">
  <script>
    const input1 = document.getElementById('input1')
    // let timer = null
    // input1.addEventListener('keyup', function () {
    //   if (timer) {
    //     clearTimeout(timer)
    //   }
    //   timer = setTimeout(() => {
    //     console.log(input1.value);
    //     timer = null
    //   }, 500)
    // })

    // debounce封装防抖函数
    function debounce(fn, delay) {
      let timer = null

      return function () {
        if (timer) {
          clearTimeout(timer)
        }

        timer = setTimeout(() => {
          fn.apply(this, arguments)
          timer = null
        }, delay)
      }
    }

    input1.addEventListener('keyup', debounce(
      function (a, b) {
        console.log(a + b);
        console.log(input1.value);
      },
      500)
    )
  </script>
</body>

</html>